import sys
import os
from PyQt5.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QPushButton,
    QFileDialog, QLabel, QSpinBox
)
from git_utils import Repo


class GitRewriteTool(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Git Commit AI Rewrite Tool")
        self.resize(600, 300)

        layout = QVBoxLayout()
        self.path_label = QLabel("📁 选择一个 Git 仓库：")
        layout.addWidget(self.path_label)

        self.select_button = QPushButton("选择仓库目录")
        self.select_button.clicked.connect(self.select_repo)
        layout.addWidget(self.select_button)

        self.commit_spin = QSpinBox()
        self.commit_spin.setValue(5)
        self.commit_spin.setMinimum(1)
        layout.addWidget(QLabel("分析最近几条提交："))
        layout.addWidget(self.commit_spin)

        self.start_button = QPushButton("开始分析提交记录")
        self.start_button.clicked.connect(self.start_analysis)
        layout.addWidget(self.start_button)

        self.setLayout(layout)

    def select_repo(self):
        path = QFileDialog.getExistingDirectory(self, "选择 Git 仓库目录")
        if path:
            self.repo_path = path
            self.path_label.setText(f"✅ 已选择: {path}")

    def start_analysis(self):
        if not hasattr(self, 'repo_path'):
            self.path_label.setText("❌ 请先选择一个 Git 仓库路径")
            return
        try:
            repo = Repo(self.repo_path)
            count = self.commit_spin.value()
            commits = list(repo.iter_commits('HEAD', max_count=count))
            for c in commits:
                print(f"{c.hexsha[:7]}: {c.message.strip()}")
        except Exception as e:
            self.path_label.setText(f"❌ 错误: {e}")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    tool = GitRewriteTool()
    tool.show()
    sys.exit(app.exec_())
